package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;

import java.util.HashMap;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;

/**
 * http://www.tianya.cn/ 天涯论坛
 *
 * @author allen
 */
public class TianYaBbsAnalyse implements AnalyseNews {


	public TianYaBbsAnalyse() {

	}

	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = { 
				"http://mytianyahelp.tianya.cn/post-.*-.*-1.shtml",
				"http://bbs.tianya.cn/post-.*-.*-1.shtml",
				"http://bbs.tianya.cn/list.jsp?item=[0-9]*&order=1",
				"http://groups.tianya.cn/tribe/.*" 
				};
		
		//http://bbs.tianya.cn/post-118167-30-1.shtml
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta bbs = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
		bbs.setUrl(url);
		String title = null;
		String content = null;
		Long date = null;
		Integer clickNum = 0;
		Integer commentNum = 0;

		Document doc = Jsoup.parse(htmltxt);
		title = doc
				.select(
						"html body div div#doc div#bd.clearfix div#post_head.atl-head h1.atl-title span.s_title")
				.text();
		if (title == null || title.trim().length() == 0) {
			title = doc
					.select(
							"html body center div.wrapper div#mainDiv div.body form#form1 div.article_box div#firstAuthor.mtime table tbody tr td table tbody tr td.mtitle div")
					.text();
			if (title == null || title.trim().length() == 0) {
			}
		}
		content = HtmlCleaner.getContentHtml(url, doc.select("div#bd div.atl-content div.bbs-content"));
		if (content == null || content.trim().length() == 0) {
			content = HtmlCleaner.getContentHtml(url, doc.select("div.article_box #content0"));
		}

		date = JSoupUtils.matchDate(doc, "时间：");
		if(date==null){
			date = DateUtils.matchDate(doc.select(".time").text());
		}

		bbs.setTitle(StringUtils.trimSpace(title));
		bbs.setContent(content);
		bbs.setDate(date);

		String clickComentstr = doc
				.select(
						"html body div div#doc div#bd.clearfix div#post_head.atl-head div.atl-menu div.atl-info span")
				.text();
		if (clickComentstr != null && clickComentstr.trim().length() != 0) {
			if (clickComentstr.indexOf("点击：") != -1) {
				String clickNumstr = clickComentstr.substring(clickComentstr
						.indexOf("点击：")
						+ "点击：".length());
				if (clickNumstr.indexOf(" ") != -1) {
					clickNumstr = clickNumstr.substring(0, clickNumstr
							.indexOf(" "));
					try {
						clickNum = Integer.parseInt(clickNumstr);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
			if (clickComentstr.indexOf("回复：") != -1) {
				String commentNumstr = clickComentstr.substring(clickComentstr
						.indexOf("回复：")
						+ "回复：".length());
				try {
					commentNum = Integer.parseInt(commentNumstr);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		} else {
			clickComentstr = doc
					.select(
							"html body center div.wrapper div#mainDiv div.body form#form1 div.article_box table tbody tr td font font")
					.text();
			if (clickComentstr != null || clickComentstr.trim().length() != 0) {
				if (clickComentstr.indexOf("访问：") != -1) {
					String clickNumstr = clickComentstr
							.substring(clickComentstr.indexOf("访问：")
									+ "访问：".length());
					if (clickNumstr.indexOf(" ") != -1) {
						clickNumstr = clickNumstr.substring(0, clickNumstr
								.indexOf(" "));
						try {
							clickNum = Integer.parseInt(clickNumstr);
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
				if (clickComentstr.indexOf("回复：") != -1) {
					String commentNumstr = clickComentstr
							.substring(clickComentstr.indexOf("回复：")
									+ "回复：".length());
					if (commentNumstr.indexOf(" ") != -1) {
						commentNumstr = commentNumstr.substring(0,
								commentNumstr.indexOf(" "));
						try {
							commentNum = Integer.parseInt(commentNumstr);
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
			}
		}

		bbs.setClickNum(clickNum);
		bbs.setCommentNum(commentNum);

		String author= JSoupUtils.matchAuthor(doc, "楼主：");
		if(StringUtils.isBlank(author)){
			Elements tmpAuthor = doc.select("div.atl-info span a");
			if(tmpAuthor.size()>0){
				author = tmpAuthor.get(0).text();
			}
		}
		bbs.setAuthor(author);
		/**
		 * 解析用于更新的地址
		 */
		String updateUrl = url;
		bbs.setUpdateUrl(updateUrl);
		return bbs;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		if (meta != null) {
			String updateUrl = meta.getUpdateUrl();
			if (updateUrl != null) {
				UrlMeta responseToURL = CrawlHTML.responseToURL(updateUrl);
				if (responseToURL != null) {
					String html = responseToURL.getHtml();
					if (html != null) {
						Integer clickNum = 0;
						Integer commentNum = 0;

						Document doc = Jsoup.parse(html);
						String clickComentstr = doc
								.select(
										"html body div div#doc div#bd.clearfix div#post_head.atl-head div.atl-menu div.atl-info span")
								.text();
						if (clickComentstr != null
								&& clickComentstr.trim().length() != 0) {
							if (clickComentstr.indexOf("点击：") != -1) {
								String clickNumstr = clickComentstr
										.substring(clickComentstr
												.indexOf("点击：")
												+ "点击：".length());
								if (clickNumstr.indexOf(" ") != -1) {
									clickNumstr = clickNumstr.substring(0,
											clickNumstr.indexOf(" "));
									try {
										clickNum = Integer
												.parseInt(clickNumstr);
									} catch (Exception e) {
										// TODO: handle exception
									}
								}
							}
							if (clickComentstr.indexOf("回复：") != -1) {
								String commentNumstr = clickComentstr
										.substring(clickComentstr
												.indexOf("回复：")
												+ "回复：".length());
								try {
									commentNum = Integer
											.parseInt(commentNumstr);
								} catch (Exception e) {
									// TODO: handle exception
								}
							}
						} else {
							clickComentstr = doc
									.select(
											"html body center div.wrapper div#mainDiv div.body form#form1 div.article_box table tbody tr td font font")
									.text();
							if (clickComentstr != null
									|| clickComentstr.trim().length() != 0) {
								if (clickComentstr.indexOf("访问：") != -1) {
									String clickNumstr = clickComentstr
											.substring(clickComentstr
													.indexOf("访问：")
													+ "访问：".length());
									if (clickNumstr.indexOf(" ") != -1) {
										clickNumstr = clickNumstr.substring(0,
												clickNumstr.indexOf(" "));
										try {
											clickNum = Integer
													.parseInt(clickNumstr);
										} catch (Exception e) {
											// TODO: handle exception
										}
									}
								}
								if (clickComentstr.indexOf("回复：") != -1) {
									String commentNumstr = clickComentstr
											.substring(clickComentstr
													.indexOf("回复：")
													+ "回复：".length());
									if (commentNumstr.indexOf(" ") != -1) {
										commentNumstr = commentNumstr
												.substring(0, commentNumstr
														.indexOf(" "));
										try {
											commentNum = Integer
													.parseInt(commentNumstr);
										} catch (Exception e) {
											// TODO: handle exception
										}
									}
								}
							}
						}
						meta.setClickNum(clickNum);
						meta.setCommentNum(commentNum);
						return meta;
					}

				}
			}
		}
		return null;
	}

	

	

	public static HashMap<String, String> getLinks(String url, String html) {
		HashMap<String, String>  ret = new HashMap<String, String>();
		try {
			html =StringUtils.substringAfter(html, "var postDatas=");
			if(html!=null) html =StringUtils.substringBefore(html, "</script>");
			if(html!=null){
				JSONArray jsonArray = JSONArray.parseArray(html);
				if(jsonArray!=null){
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject json = jsonArray.getJSONObject(i);
						String categoryId = json.getString("categoryId");
						String articleId = json.getString("articleId");
						String u = "http://bbs.tianya.cn/post-"+categoryId+"-"+articleId+"-1.shtml"	;
						String title = json.getString("title");
						ret.put(u, title);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
}
